<?php

namespace addons\yunfood\controller;

use addons\yunfood\library\Logic;
use addons\yunfood\library\Super;
use addons\yunfood\model\FoodCategory;
use addons\yunfood\model\FoodLike;
use addons\yunfood\model\Food as FoodModel;
use addons\yunfood\model\FoodParam;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 菜品接口
 */
class Food extends BaseApi
{
    // 获取菜品列表
    public function getFoodList()
    {
        $keyword = $this->request->post('keyword');
        $group = $this->request->post('group');

        // 校验门店
        $this->validShop(false);

        // 数据列表
        $query = FoodModel::with('categoryData')->show()
            ->where('find_in_set(:sid, `shop_ids`) or shop_ids=\'\'', ['sid' => $this->shopId]);
        if ($keyword) {
            $query->where('name', 'like', '%' . $keyword . '%');
        }
        if ($group === 'sale') {
            $query->where('count_left', '>', 0);
        }
        $dataList = $query->order(['weight' => 'DESC', 'id' => 'DESC'])->select();
        $dataList = Super::arrayGetSet($dataList, [
            'id',
            'name',
            'cover_url',
            'category_id',
            'category_name' => function ($item) {
                return $item->categoryData->name ?? '--';
            },
            'multi_spec',
            'price',
            'market_price',
            'count_left',
            'count_sale',
            'count_like'
        ], true);
        $result['total'] = count($dataList);
        $dataListMap = Super::arrayIndex($dataList, null, 'category_id');
        $groupList = [];
        $categoryList = FoodCategory::show()
            ->where('find_in_set(:sid, `shop_ids`) or shop_ids=\'\'', ['sid' => $this->shopId])
            ->order(['weigh' => 'ASC', 'id' => 'DESC'])->select();
        foreach ($categoryList as $item) {
            if ($dataList = $dataListMap[$item->id] ?? null) {
                $groupList[] = [
                    'id'    => $item->id,
                    'name'  => $item->name,
                    'items' => $dataList
                ];
            }
        }
        $result['group_list'] = $groupList;

        $this->success('success', $result);
    }

    // 获取菜品详情
    public function getFoodDetail()
    {
        // 校验门店
        $this->validShop(false);

        $foodId = $this->request->post('id');
        if (! $food = FoodModel::get(['id' => $foodId])) {
            $this->error('菜品不存在');
        }
        if ($food->status != FoodModel::STATUS_NORMAL) {
            $this->error('菜品已下架');
        }
        if ($food->shop_ids) {
            if (! in_array($this->shopId, explode(',', $food->shop_ids))) {
                $this->error('当前门店没有此菜品');
            }
        }

        $result = Super::arrayGetSet($food, [
            'id',
            'name',
            'cover_url',
            'category_id',
            'category_name' => function ($item) {
                return $item->categoryData->name ?? '--';
            },
            'multi_spec',
            'spec_list'     => function ($item) {
                return Super::arrayGetSet($item->specListData, [
                    'id',
                    'name',
                    'items' => function ($item) {
                        return explode(',', $item->items);
                    }
                ], true);
            },
            'sku_list'      => function ($item) {
                return Super::arrayGetSet($item->skuListData, [
                    'id',
                    'spec_text',
                    'cover_url',
                    'market_price',
                    'price',
                    'count_left',
                    'count_sale',
                    'state'
                ], true);
            },
            'attr_list'     => function ($item) {
                if (! $item->attr_ids) {
                    return [];
                }
                $paramList = FoodParam::where('id', 'in', explode(',', $item->attr_ids))->select();

                return Super::arrayGetSet($paramList, [
                    'id',
                    'name',
                    'items' => function ($item) {
                        return $item->items ? explode(',', $item->items) : [];
                    }
                ], true);
            },
            'note_list'     => function ($item) {
                if (! $item->note_ids) {
                    return [];
                }
                $result = [];
                $paramList = FoodParam::where('id', 'in', explode(',', $item->note_ids))->select();
                foreach ($paramList as $param) {
                    if (! $param['items']) {
                        continue;
                    }
                    $result = array_merge($result, explode(',', $param['items']));
                }
                $result = array_unique($result);

                return $result;
            },
            'addon_list'    => function ($item) {
                if (! $item->addon_ids) {
                    return [];
                }
                $foodIds = [];
                $paramList = FoodParam::where('id', 'in', explode(',', $item->addon_ids))->select();
                foreach ($paramList as $param) {
                    if (! $param['items']) {
                        continue;
                    }
                    $foodIds = array_merge($foodIds, explode(',', $param['items']));
                }
                $foodIds = array_unique($foodIds);
                $foodList = FoodModel::where('id', 'in', $foodIds)->where('multi_spec', 0)->show()->select();

                return Super::arrayGetSet($foodList, ['id', 'name', 'market_price', 'price', 'count_left'], true);
            },
            'market_price',
            'price',
            'count_left',
            'count_sale',
            'count_like',
            'is_like'       => function ($item) {
                return FoodLike::get([
                    'food_id' => $item->id,
                    'user_id' => $this->userId,
                    'status'  => FoodLike::STATUS_YES
                ]) ? 1 : 0;
            }
        ]);

        $this->success('success', $result);
    }

    // 获取收藏列表
    public function getLikeList()
    {
        // 数据列表
        $query = FoodLike::with(['foodData', 'foodData.categoryData'])
            ->where(['user_id' => $this->userId, 'status' => FoodLike::STATUS_YES])
            ->order(['id' => 'DESC']);
        $result = $query->paginate($this->request->post('page_size', 10), false);
        $result = Logic::getPageData($result, [
            'id',
            'food_id',
            'food_data' => function ($item) {
                if (! $food = $item->foodData) {
                    return null;
                }

                return Super::arrayGetSet($food, [
                    'id',
                    'name',
                    'cover_url',
                    'category_id',
                    'category_name' => function ($item) {
                        return $item->categoryData->name ?? '--';
                    },
                    'price',
                    'multi_spec'
                ]);
            },
            'created_at',
        ]);

        $this->success('success', $result);
    }

    // 是否收藏
    public function handleLike()
    {
        $action = $this->request->post('action');
        $foodId = $this->request->post('food_id');
        if ($foodLike = FoodLike::get(['food_id' => $foodId, 'user_id' => $this->userId])) {
            if ($action === 'yes') {
                if ($foodLike->status != FoodLike::STATUS_NO) {
                    $this->error('已经收藏过了');
                }
            } elseif ($action === 'no') {
                if ($foodLike->status != FoodLike::STATUS_YES) {
                    $this->error('已经取消收藏了');
                }
            }
            if ($foodLike->updated_at > (time() - 5)) {
                $this->error('你操作得太快了');
            }
        } else {
            if ($action === 'no') {
                $this->error('还未收藏过');
            }
            if (! $food = FoodModel::get(['id' => $foodId])) {
                $this->error('菜品不存在');
            }
            $foodLike = new FoodLike();
            $foodLike->food_id = $food->id;
            $foodLike->user_id = $this->userId;
        }
        $foodLike->status = $action === 'yes' ? FoodLike::STATUS_YES : FoodLike::STATUS_NO;

        Db::startTrans();
        try {
            $foodLike->save();
            if ($action === 'yes') {
                FoodModel::where('id', $foodId)->setInc('count_like');
            } else {
                FoodModel::where('id', $foodId)->setDec('count_like');
            }
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('success', []);
    }
}
